<template>
  <xDialog v-model="isShow" width="650px" @open="handleOpen" @closed="handleClose" title="分配菜单与按钮的权限">
    <el-tree
      ref="tree"
      :data="menuArr"
      show-checkbox
      node-key="id"
      :default-expanded-keys="[1]"
      :default-checked-keys="selectArr"
      :props="defaultProps"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </xDialog>
</template>

<script setup lang="ts">
import { reqAllMenuList, reqSetPermisstion } from '@/api/acl/role'
import { ref, computed, defineEmits, defineProps } from 'vue'
import useDialog from '@/hooks/dialog'
import { ElMessage } from 'element-plus'
const props = defineProps({
  modalData: { required: false, type: Object, default: () => {} },
  modalType: { required: false, type: String, default: 'add' }
})
let tree = ref()
const menuArr = ref([])
let selectArr = ref<number[]>([])
const defaultProps = {
  children: 'children',
  label: 'name'
}

const { open, isShow, handleOpen, handleClose, cancel } = useDialog({
  props: props,
  beforeOpenFunction: () => {
    setPermisstion()
  }
})
const setPermisstion = async () => {
  let result = await reqAllMenuList(props.modalData.id as number)
  console.log(result)
  menuArr.value = result.data
  selectArr.value = filterSelectArr(menuArr.value, [])
}
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })

  return initArr
}
const save = async () => {
  //选中节点的ID
  let arr = tree.value.getCheckedKeys()
  //半选的ID
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let result = await reqSetPermisstion(props.modalData.id as number, permissionId)
  if (result.code === 200) {
    //抽屉关闭
    isShow.value = false
    //提示信息
    ElMessage({ type: 'success', message: '分配权限成功' })
  }
}

defineExpose({
  open
})
</script>

<style scoped lang="scss"></style>
